#include "i2c.h"
#include "i2cEprom.h"

unsigned char I2CEPROM_SetWriteAddress( unsigned int addr )
{
	for( unsigned char i=0; i<20;i++)
	{	
		I2C_Start();
		if	( I2C_Write( 0xa0 ) && I2C_Write( addr>>8 ) && I2C_Write( addr & 0xff ) )
		{
			return 1;			
		}
		I2C_Stop();
	}	
	return 0;
}


unsigned char I2CEPROM_SetReadAddress( unsigned int addr )
{
	for( unsigned char i=0; i<20;i++)
	{	
		if ( I2CEPROM_SetWriteAddress( addr ) )
		{
			I2C_Start();
			if ( I2C_Write( 0xa1 ) )
			{
				return 1;			
			}
		}
		I2C_Stop();
	}	
	return 0;
}

void I2CEPROM_SimpleWrite( unsigned int addr, unsigned char *source, unsigned char length )
{
	char res_ok = 0;
	for ( unsigned int i = addr; i< (addr + length); )
	{
		if ( res_ok == 0 )
		{
			I2C_Stop();
			res_ok = I2CEPROM_SetWriteAddress( i );
		}
		else 
		{
			res_ok = I2C_Write( *source );
			if ( res_ok )
			{
				i++;
				source++;
			}
		}
	}
	I2C_Stop();
}

void I2CEPROM_SimpleRead( unsigned int addr, unsigned char *dest, unsigned char length )
{
	char res_ok = 0;
	for ( unsigned int i = 0; i< length; )
	{
		if ( res_ok == 0 )
		{
			I2C_Stop();
			res_ok = I2CEPROM_SetReadAddress( addr + i );
		}
		else 
		{
			*dest = I2C_Read( (length - i) != 1 );
			i++;
			dest++;
		}
	}
	I2C_Stop();
}

unsigned int I2CEPROM_Verify( unsigned int addr, unsigned char *source, unsigned char length )
{
	char res_ok = 0;
	for ( unsigned int i = 0; i< length; )
	{
		if ( res_ok == 0 )
		{
			I2C_Stop();
			res_ok = I2CEPROM_SetReadAddress( addr + i );
		}
		else 
		{
			if ( I2C_Read( (length - i) != 1 ) != *source )
			{
				I2C_Stop();			
				return i;
			}
			i++;
			source++;
		}
	}
	I2C_Stop();

	return length;
}

void I2CEPROM_Read( unsigned int addr, unsigned char *dest, unsigned char length )
{
	do
	{
		I2CEPROM_SimpleRead( addr, dest, length );
	}
	while ( I2CEPROM_Verify( addr, dest, length ) != length );
}

void I2CEPROM_Write( unsigned int addr, unsigned char *dest, unsigned char length )
{
	do
	{
		I2CEPROM_SimpleWrite( addr, dest, length );
	}
	while ( I2CEPROM_Verify( addr, dest, length ) != length );
}

unsigned char I2CEPROM_peek( unsigned int addr )
{
	char c;

	I2CEPROM_Read( addr, &c, 1);

	return c;
}

/*
void I2cEprom()
{
	I2C_Init();
	//write
	I2C_Start();
	Ack( I2C_Write( 0xa0 ) );
	Ack( I2C_Write( 0 ) );
	Ack( I2C_Write( 0 ) );

	Ack( I2C_Write( 0xca ) );
	Ack( I2C_Write( 0xfe ) );

	I2C_Stop();

	//read
	I2C_Start();
	Ack( I2C_Write( 0xa0 ) );
	Ack( I2C_Write( 0 ) );
	Ack( I2C_Write( 0 ) );
	
	I2C_Start();
	Ack( I2C_Write( 0xa0+1 ) );

	PrintHex8( I2C_Read(1) );
	PrintHex8( I2C_Read(1) );
	PrintHex8( I2C_Read(1) );
	PrintHex8( I2C_Read(0) );

	I2C_Stop();

}
*/
